package com.toman.ui.my;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.squareup.picasso.Picasso;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.SysUserEntity;
import com.toman.MyApplication;
import com.toman.R;
import com.toman.Util.CircleTransform;
import com.toman.Util.IntentUtils;
import com.toman.Util.ProgressDialogUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.StringUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.toolbar.ToolBarWhiteActivity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class InfActivity extends ToolBarWhiteActivity {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.rl_head)
    RelativeLayout rlHead;
    @BindView(R.id.textView2)
    TextView textView2;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.rl_name)
    RelativeLayout rlName;
    @BindView(R.id.tv_username)
    TextView tvUsername;
    @BindView(R.id.tv_job)
    TextView tvJob;
    @BindView(R.id.tv_account)
    TextView tvAccount;
    @BindView(R.id.tv_email)
    TextView tvEmail;
    @BindView(R.id.rl_email)
    RelativeLayout rlEmail;
    @BindView(R.id.tv_company)
    TextView tvCompany;
    private PopupWindow popupWindow;
    public static final int IMAGE_PICKER = 0;
    MyApplication myApplication;
    Dialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inf);
        ButterKnife.bind(this);
        initToolBar("", getResources().getColor(R.color.white));
        initHandler();
        initView();
    }

    private void initView() {
        myApplication = (MyApplication) getApplication();

    }

    @Override
    protected void onResume() {
        super.onResume();
        get();
    }

    private void showUserJava8Feature() {
        //测试lambda
        //声明生命一个变量addition,其为lambda表达式,这个表达式有两个参数,用括号括起来,分别为a和
        //其执行的表示式为a+b,并返回
        //可以看出lambda即像c++的指针操作,也像java的内联函数的使用
        MathOperation addition = (int a, int b) -> a + b;
        //当执行operate方法的时候,采用内联函数的方式执行表达式a + b;
        Log.d("hwj", "**showUserJava8Feature addition: 10 + 5 =  **" + operate(10, 5, addition));
    }

    interface MathOperation {
        int operation(int a, int b);
    }

    private int operate(int a, int b, MathOperation mathOperation) {
        return mathOperation.operation(a, b);
    }

    @OnClick({R.id.iv_head, R.id.rl_name, R.id.rl_email})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_head:
                showPop(view);

                break;
            case R.id.rl_name:
                Bundle bundle = new Bundle();
                bundle.putString("type", "姓名");
                bundle.putString("content", tvName.getText().toString());

                IntentUtils.startActivity(this, InfEditActivity.class, bundle);
                break;
            case R.id.rl_email:
                bundle = new Bundle();
                bundle.putString("type", "邮箱");
                bundle.putString("content", tvEmail.getText().toString());
                IntentUtils.startActivity(this, InfEditActivity.class, bundle);
                break;
        }
    }

    /*
        显示修改头像PopupWindow
     */
    public void showPop(View v) {
        View view = LayoutInflater.from(this).inflate(R.layout.user_photo, null, false);
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setAnimationStyle(R.style.popwin_anim_style);
        WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        lp.alpha = 0.5f;
        this.getWindow().setAttributes(lp);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = InfActivity.this.getWindow().getAttributes();
                lp.alpha = 1.0f;
                InfActivity.this.getWindow().setAttributes(lp);
            }
        });
        //拍照
        TextView photo_photo = (TextView) view.findViewById(R.id.photo_photo);
        //选择相册
        TextView photo_album = (TextView) view.findViewById(R.id.photo_album);
        //取消
        TextView photo_dimss = (TextView) view.findViewById(R.id.photo_dimss);

        photo_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ViewUtil.checkPer(InfActivity.this)) {
                    Intent intent = new Intent(InfActivity.this, ImageGridActivity.class);
                    intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                    startActivityForResult(intent, IMAGE_PICKER);
                    popupWindow.dismiss();
                }
            }
        });

        photo_album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转选择相册
                Intent intent = new Intent(InfActivity.this, ImageGridActivity.class);
                startActivityForResult(intent, IMAGE_PICKER);
                popupWindow.dismiss();
            }
        });

        photo_dimss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 5);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                myApplication.getImagePicker().getImageLoader().displayImage(this, images.get(0).path, ivHead, 500, 500);
//                Picasso.with(getApplicationContext()).load(images.get(0).path).error(R.mipmap.my_icon_head).transform(new CircleTransform()).into(ivHead);
                Map<String, String> map = new HashMap<String, String>();
                map.put("token", token);
                dialog = ProgressDialogUtils.showProgressDialog(this, "正在上传中", "请稍后");
                List<String> list = new ArrayList<>();
                list.add(images.get(0).path);
                upload((HashMap<String, String>) map, list);
                ToastUtil.print("url:" + images.get(0).path);
            }
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1002:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //用户同意授权
                    Intent intent = new Intent(InfActivity.this, ImageGridActivity.class);
                    intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                    startActivityForResult(intent, IMAGE_PICKER);

                } else {
                    //用户拒绝授权
                    ViewUtil.Dialog(this);
                }
                break;
        }
    }


    public void get() {
        String token = (String) SPUtils.get(getApplicationContext(), "token", "");
        OkHttpUtils
                .get(NewBaseUrl.user_info_get+SPUtils.get(getApplicationContext(),"userid",""))
                .params("token", token)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "人员信息: " + result);

                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());
                        if (code == 0) {
                            SysUserEntity bean = (SysUserEntity) JSON.parseObject(jsonObj.getString("user"), SysUserEntity.class);

                            try {
                                tvName.setText(bean.getRealName());
                                tvJob.setText(bean.getPostInformation());
                                tvEmail.setText(bean.getEmail());
tvCompany.setText(bean.getCompanyName());
                                tvUsername.setText(bean.getUsername());
                                tvAccount.setText(bean.getMobile());
                                if (!StringUtils.isEmpty(bean.getPhotoUrl())) {
                                    Picasso.with(getApplicationContext()).load(bean.getPhotoUrl()).error(R.mipmap.my_icon_head).transform(new CircleTransform()).into(ivHead);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    private void upload(HashMap<String, String> map, List<String> paths) {
        final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
        //创建OkHttpClient实例
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS).build();
        MultipartBody.Builder mbody = new MultipartBody.Builder().setType(MultipartBody.FORM);

//遍历map中所有参数到builder
        for (String key : map.keySet()) {
            mbody.addFormDataPart(key, map.get(key));
        }


        for (String path : paths) {
            File file = new File(path);
            if (file.exists()) {
                mbody.addFormDataPart("file", file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
            }
            // builder.addFormDataPart("file[]", null, RequestBody.create(MEDIA_TYPE_PNG, new File(path)));
        }


        //构建请求体
        RequestBody requestBody = mbody.build();
        final Request request = new Request.Builder()
                .header("Authorization", "Client-ID " + "...")

                .url(NewBaseUrl.user_update_post_photo)
                .post(requestBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                dialog.dismiss();

                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();

                Log.i("新增报修", result);
                JSONObject jsonObj = JSON.parseObject(result);
                int code = jsonObj.getInteger("code");
                ViewUtil.lagout(code, getApplicationContext());
                if (code == 0) {
                    dialog.dismiss();
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = jsonObj.getString("msg");//可以是基本类型，可以是对象，可以是List、map等；
                    mHandler.sendMessage(msg);
                } else {
                    dialog.dismiss();

//                    ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                    Message msg = new Message();
                    msg.what = 2;
                    msg.obj = jsonObj.getString("msg");//可以是基本类型，可以是对象，可以是List、map等；
                    mHandler.sendMessage(msg);
                }
            }
        });


    }

    private void initHandler() {
        mHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {

                    case 1:
                        get();

                        ToastUtil.makeText(getApplicationContext(), (String) msg.obj);
                        break;
                    case 2:
                        ToastUtil.makeText(getApplicationContext(), (String) msg.obj);

                        break;
                    default:
                        break;
                }
            }
        };
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog != null) {
            dialog.dismiss();
        }

    }
}
